package com.ls.lserp.modules.produce.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.InventoryRequestEx;
import com.ls.lserp.modules.material.service.InventoryRequestExService;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.produce.entity.ProduceLicense;
import com.ls.lserp.modules.produce.entity.ProduceNotice;
import com.ls.lserp.modules.produce.service.ProduceLicenseService;
import com.ls.lserp.modules.produce.service.ProduceNoticeService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/produce/notice/")
public class ProduceNoticeController extends BaseController {


    @Autowired
    private ProduceNoticeService produceNoticeService;

    //生产制单
  	@Autowired
  	private ProduceLicenseService produceLicenseService;
  	
  	//出库申请
  	@Autowired
	private InventoryRequestExService inventoryRequestExService;
    
    @Autowired
    Configuration freemarkerConfiguration;

    @ModelAttribute
    public ProduceNotice get(@RequestParam(required = false) String id) {

        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {

            // 执行查询语句 查询基本信息
            return produceNoticeService.findByID (Long.parseLong (id));
        } else {

            // 若为空，实例化
            return new ProduceNotice ();
        }
    }

    /**
     * 生产通知单一览画面
     *
     * @return
     */
    @RequestMapping(value = {""})
    public String producePlan(Model model) {
        List <ProduceNotice> groupList = produceNoticeService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        return "modules/produce/produceNotice";

    }

    /**
     * 拼接一览画面
     *
     * @param values
     * @return
     */
    @RequiresPermissions("produce:notice:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(ProduceNotice produceNotice, HttpServletRequest request, HttpServletResponse response,
                             Model model, String[] values) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "produceNotice");
        // 画面取得的检索项目
        long userGroupID = produceNotice.getUserGroupID ();
        String ognizationName = produceNotice.getOgnizationName ();
        String dateStart = produceNotice.getDateStart ();
        String dateEnd = produceNotice.getDateEnd ();
        String ulSelected = produceNotice.getUlSelected ();
        // 拼接字符串供分页使用
        String searchParam = "&userGroupID=" + userGroupID + "&ognizationName=" + ognizationName + "&dateStart=" + dateStart + "&dateStart=" + dateStart + "&dateEnd=" + dateEnd + "&ulSelected=" + ulSelected;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page <ProduceNotice> page = produceNoticeService.findProduceNoticeList (new Page <ProduceNotice> (request, response),
                produceNotice);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("noticeList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        map.put("springMacroRequestContext", new RequestContext (request));
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("produceNoticeList.ftl"), map);
        listMap.put ("produceNotice", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }


    /**
     * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     *
     * @param filePath
     * @return html
     */
    public String readTxtFile(String filePath) {
        String strHtml = "";
        try {
            String encoding = "UTF-8";
            File file = new File (filePath);
            // 判断文件是否存在
            if (file.isFile ()) {
                InputStreamReader read = new InputStreamReader (
                        // 考虑到编码格式
                        new FileInputStream (file), encoding);
                BufferedReader bufferedReader = new BufferedReader (read);
                String lingText = null;
                while ((lingText = bufferedReader.readLine ()) != null) {
                    strHtml += lingText;
                }
                read.close ();
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return strHtml;
    }

    /**
     * 进入编辑页面
     *
     * @param orderMateriel
     * @param model
     * @return
     */
    @RequiresPermissions("produce:notice:edit")
    @RequestMapping(value = "form")
    public String form(OrderMateriel orderMateriel, Model model, HttpSession session) {

        orderMateriel = produceNoticeService.getOrderInfo (orderMateriel.getIndentId ());

        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("orderMateriel", orderMateriel);

        // 返回页面地址
        return "modules/produce/produceNoticeCreate";
    }

    /**
     * 创建生产通知单信息窗口
     *
     * @return
     */
    @RequiresPermissions("produce:notice:view")
    @RequestMapping(value = {"createNotice"})
    public String createNotice(ProduceNotice produceNotice, Model model) {
        List <ProduceNotice> groupList = produceNoticeService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        produceNotice.preInsert ();
        model.addAttribute ("produceNotice", produceNotice);
        return "modules/produce/produceNoticeCreate";
    }

    /**
     * 查看备料详情画面
     *
     * @return
     */
    @RequiresPermissions("produce:notice:view")
    @RequestMapping(value = {"showStockDetails"})
    public String showStockDetails(ProduceNotice produceNotice, Model model) {
    	List<OrderMateriel> stockDetailList = produceNoticeService.findStockDetails(produceNotice);
    	model.addAttribute ("stockDetailList", stockDetailList);
        model.addAttribute ("produceNotice", produceNotice);
        return "modules/produce/produceNoticeStockDetails";
    }
    
    /**
     * 新增一条生产制单
     *
     * @return
     */
    @RequiresPermissions("produce:notice:view")
    @RequestMapping(value = {"createNewLicense"})
    public String createNewLicense(ProduceNotice produceNotice, Model model,HttpServletRequest request,HttpServletResponse response) {
        //String flag = "false";
    	try {
    		List<ProduceLicense> customerList = produceLicenseService.findCustomerList();
			List<ProduceLicense> groupList = produceLicenseService.findGroupList();
			ProduceLicense produceLicense = produceNoticeService.createNewLicense (produceNotice);
			List<ProduceLicense> indentList = produceLicenseService.findIndentNOList(produceLicense.getOgnizationID());
			produceLicense.setIndentList(indentList);
			produceLicense.preInsert();
			produceLicense.setCustomerList(customerList);
			produceLicense.setGroupList(groupList);
			//生产通知单信息
			produceNotice = produceNoticeService.getNotice (produceNotice);
	        model.addAttribute ("groupList", groupList);
	        model.addAttribute ("orderMateriel", produceNotice.getOrderMateriel ());
	        model.addAttribute ("produceNotice", produceNotice);
        	//flag = "true";
    		model.addAttribute ("produceLicense", produceLicense);
    		model.addAttribute ("produceNoticeId", produceNotice.getId());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
        return "modules/produce/produceLicenseCreate";
    }
    
    /**
     * 出库申请画面
     * @return
     */
    @RequestMapping(value = {"inventoryRequestEx"})
    public String inventoryRequestEx(InventoryRequestEx inventoryRequestEx,Model model) {
    	// 获取当前用户
		User curLoginUser = inventoryRequestEx.getCurrentUser();
		List<InventoryRequestEx> productionList = inventoryRequestExService.findProductionList();
		inventoryRequestEx.setProductionList(productionList);
		/*inventoryRequestEx.setInventoryRequestNo("HLOUT"+DateUtils.formatDate(new Date(), "yyMMddHHmmss"));*/
    	// 出库单条码
    	inventoryRequestEx.setStockBarCode(SequenceUtil.inventoryRequestbarcode().getReturnCode());
    	// 申请人
    	inventoryRequestEx.setRequestUser(curLoginUser.getFirstName() + curLoginUser.getLastName());
    	inventoryRequestEx.setRequestUserId(curLoginUser.getId());
    	// 申请日期
    	inventoryRequestEx.setRequestDate(new Date());
    				
    	// 下拉菜单（客供入库）
    	inventoryRequestEx.setInventoryCategory(ResourcesUtil.getConfig("outbound_category_produce"));
    	List<ProduceLicense> customerList = produceLicenseService.findCustomerList();
    	// 下拉合同号
    	model.addAttribute("imageStr","produceNotice");
    	model.addAttribute("inventoryRequestEx",inventoryRequestEx);
    	model.addAttribute("bigContractId",inventoryRequestEx.getContractID());
    	model.addAttribute("customerList",customerList);
        return "modules/material/inventoryRequestExCreate";
    }
    
    /**
     * 查看一条生产通知单信息
     *
     * @return
     */
    @RequiresPermissions("produce:notice:view")
    @RequestMapping(value = {"viewNotice"})
    public String viewNotice(ProduceNotice produceNotice, Model model) {
        produceNotice = produceNoticeService.getNotice (produceNotice);
        List <ProduceNotice> groupList = produceNoticeService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        model.addAttribute ("producePlan", produceNotice.getProducePlan ());
        model.addAttribute ("orderMateriel", produceNotice.getOrderMateriel ());
        model.addAttribute ("produceNotice", produceNotice);
        return "modules/produce/produceNoticeShow";
    }
    /**
     * 编辑生产通知单信息窗口
     *
     * @return
     */
    @RequiresPermissions("produce:notice:view")
    @RequestMapping(value = {"editNotice"})
    public String editNotice(ProduceNotice produceNotice, Model model) {
        produceNotice = produceNoticeService.getNotice (produceNotice);
        List <ProduceNotice> groupList = produceNoticeService.findGroupList ();
        model.addAttribute ("groupList", groupList);
        model.addAttribute ("producePlan", produceNotice.getProducePlan ());
        model.addAttribute ("orderMateriel", produceNotice.getOrderMateriel ());
        model.addAttribute ("produceNotice", produceNotice);
        return "modules/produce/produceNoticeCreate";
    }
    /**
     * 创建编辑保存生产通知单
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:notice:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(ProduceNotice produceNotice, HttpServletRequest request, HttpServletResponse response,
                       Model model) throws ResourceException {
        // 判断id是否为null （判断新建或修改）
        if (produceNotice.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProduceNotice produceNoticeNew = get (produceNotice.getId ().toString ());
            // 判断数据是否删除
            if (produceNoticeNew == null || BaseEntity.DEL_FLAG_DELETE.equals (produceNoticeNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
            // 排他处理
            if (produceNotice.getVersion () == get (produceNotice.getId ().toString ()).getVersion ()) {
                // 版本号加1
                produceNotice.setVersion (produceNotice.getVersion () + 1);
            } else {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }
        String flag = "false";
        try {
        	// 保存数据
        	produceNoticeService.saveProduceNotice (produceNotice);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return renderString (response, flag );
		}
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));
    }

    /**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param orderMateriel
	 * @param request
	 * @param response
	 * @param model
	 * @return searchIndentList
	 * @throws ResourceException
	 */
	@RequiresPermissions("customization:nuclearmaterial:view")
	@RequestMapping(value = { "searchIndentList" })
	@ResponseBody
	public String searchIndentList(OrderMateriel orderMateriel, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();

		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "indent");

		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&customerIndentNo=");
		searchParam.append(orderMateriel.getCustomerIndentNo());
		searchParam.append("&styleCustomerNo=");
		searchParam.append(orderMateriel.getStyleCustomerNo());
		searchParam.append("&ognizationName=");
		searchParam.append(orderMateriel.getOgnizationName());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<OrderMateriel> page = produceNoticeService.findIndentList(new Page<OrderMateriel>(request, response),orderMateriel);
		String strHtml = "";
		try{
			Map<String, Object>  map = new HashedMap();
			map.put("indentList",page.getList());
			map.put("pageNo",page.getPageNo());
			map.put("pageSize",page.getPageSize());
			strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("indentSelect.ftl"), map);
		}
		catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
		}
		
		listMap.put("indent", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
    
    /**
     * 提交生产计划
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:notice:edit")
    @RequestMapping(value = "commit")
    @ResponseBody
    public String commit(ProduceNotice produceNotice, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (produceNotice.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProduceNotice produceNoticeNew = get (produceNotice.getId ().toString ());
            // 判断数据是否删除
            if (produceNoticeNew == null || BaseEntity.DEL_FLAG_DELETE.equals (produceNoticeNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
            // 排他处理
            if (produceNotice.getVersion () == get (produceNotice.getId ().toString ()).getVersion ()) {
                // 版本号加1
                produceNotice.setVersion (produceNotice.getVersion () + 1);
            } else {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }

        // 保存数据
        produceNoticeService.updateStatus (produceNotice);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 删除生产计划
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("produce:notice:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(ProduceNotice produceNotice, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (produceNotice.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            ProduceNotice produceNoticeNew = get (produceNotice.getId ().toString ());
            // 判断数据是否删除
            if (produceNoticeNew == null || BaseEntity.DEL_FLAG_DELETE.equals (produceNoticeNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
            // 排他处理
            if (produceNotice.getVersion () == get (produceNotice.getId ().toString ()).getVersion ()) {
                // 版本号加1
                produceNotice.setVersion (produceNotice.getVersion () + 1);
            } else {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }
        // 保存数据
        produceNoticeService.deleteProducePlan (produceNotice);
        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }
}
